package com.changgou.consume.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.consume.config.RabbitMQConfig;
import com.changgou.consume.service.SeckillOrderService;
import com.changgou.seckill.pojo.SeckillOrder;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: HuangFu
 * @Date: 2020/2/24 15:12
 * @Description:
 */
@Component
public class SeckillOrderListener {

    @Autowired
    private SeckillOrderService seckillOrderService;


    @RabbitListener(queues = RabbitMQConfig.SECKILL_ORDER_KEY)
    public void consumeSeckillOrder(Message message, Channel channel){
        //设置预抓取总数
        try {
            channel.basicQos(300);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取订单数据
        SeckillOrder seckillOrder = JSON.parseObject(message.getBody(), SeckillOrder.class);
        if(seckillOrder == null){
            return;
        }
        //持久化订单数据
        int result = seckillOrderService.createOrder(seckillOrder);
        if(result >0){
            try{
                //手动签收
                //deliveryTag  消息标识, multiple是否批量签收
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }catch (Exception e){
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }

}
